package com.example.onlineeducation.ui.topic

import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.onlineeducation.App
import com.example.onlineeducation.base.BaseFragment
import com.example.onlineeducation.data.entity.OptionEntity
import com.example.onlineeducation.databinding.StudyPractiseFragmentBinding
import com.example.onlineeducation.utils.PractiseProblemAdapterUtil
import com.example.onlineeducation.viewmodel.StudyContentVM
import com.yc.jetpacklib.extension.ycIsNotEmpty
import com.yc.jetpacklib.net.doFail
import com.yc.jetpacklib.net.doSuccess
import com.yc.jetpacklib.utils.showSingleBtnDialog
import com.yc.jetpacklib.widget.dialog.YcCommonDialog

class StudyPractiseFragment(private val mTopicId: String) : BaseFragment<StudyPractiseFragmentBinding>(StudyPractiseFragmentBinding::inflate) {

    private val mCommonDialog: YcCommonDialog by lazy {
        YcCommonDialog(requireActivity(), requireActivity())
    }
    private val mViewModel: StudyContentVM by activityViewModels()
    private var mChapterId: String? = null//当前章节id
    private lateinit var mProId: String
    private val mProblemUtil by lazy { PractiseProblemAdapterUtil() }
    private var mOptionList = mutableListOf<OptionEntity>()
    private var needLoadData = true//需要加载数据

    override fun onResume() {
        super.onResume()
        if (mChapterId != (activity as StudyContentActivity).mChapterId) {//判断章节是否有变化
            mChapterId = (activity as StudyContentActivity).mChapterId
            needLoadData = true
        }
        if (needLoadData) {
            mProblemUtil.initRecyclerView(mViewBinding.rvProblem)
            getData()
            needLoadData = false
        } else {
            mViewBinding.clStudyPractiseFragment.visibility = View.VISIBLE
        }
    }

    override fun onPause() {
        super.onPause()
        mViewBinding.clStudyPractiseFragment.visibility = View.GONE
    }

    override fun StudyPractiseFragmentBinding.initView(view: View, savedInstanceState: Bundle?) {
        App.mInstant.mViewModel.mProInfoEntity.observe {
            mProId = it!!.proId
        }

        rvProblem.layoutManager = object : LinearLayoutManager(requireActivity(), HORIZONTAL, false) {
            override fun canScrollHorizontally(): Boolean {
                return false
            }
        }

        mProblemUtil.apply {
            initRecyclerView(rvProblem)
            mProblemNumCall = { currentPosition: Int, itemCount: Int ->
                groupDefault.visibility = View.VISIBLE
                groupFailure.visibility = View.GONE
            }
            mSubmitSingleCall = { currentPosition: Int, itemCount: Int ->
                if (mProblemUtil.getData()[currentPosition].questionId.ycIsNotEmpty()) {
                    dealWithOptionList(mProblemUtil.getData()[currentPosition].optionList)
                    mViewModel.submitPractiseOptions(
                        mProId, mTopicId, mChapterId!!,
                        mProblemUtil.getData()[currentPosition].questionId!!,
                        mOptionList
                    )
                } else {
                    showSingleBtnDialog(mCommonDialog, "题目id无效，请联系管理员")
                }
            }
            mFinishCall = {
                showSingleBtnDialog(mCommonDialog, "已全部答完，请返回学习") {
                    (activity as StudyContentActivity).switchStudyMaterialFragment()
                    needLoadData = true
                }

            }
        }


        btnReAnswer.setOnClickListener {
            mProblemUtil.revertOption()
        }

        btnNext.setOnClickListener {
            mProblemUtil.next()
        }
        btnSubmit.setOnClickListener {
            mProblemUtil.submitSingle()
        }

        mViewModel.mPractiseSubmitResult.observe { ycResult ->
            ycResult.doSuccess {
                if (it == null) {
                    mProblemUtil.next()
                } else {
                    groupDefault.visibility = View.GONE
                    groupFailure.visibility = View.VISIBLE
                    mProblemUtil.showCorrectAnswer(it)
                }
            }.doFail {
                showSingleBtnDialog(mCommonDialog, "这道题没有答案，请联系管理员")
                groupDefault.visibility = View.GONE
                groupFailure.visibility = View.VISIBLE
            }
        }

        mViewModel.mPractiseQuestionList.observe { ycResult ->
            ycResult.doSuccess {
                if (it.ycIsNotEmpty()) {
                    mProblemUtil.addAll(it)
                    clStudyPractiseFragment.visibility = View.VISIBLE
                } else {
                    showSingleBtnDialog(mCommonDialog, "此学习，暂无题目") {
                        (activity as StudyContentActivity).switchStudyMaterialFragment()
                    }
                }
            }.ycShowNetError()
        }
    }

    private fun getData() {
        if (mChapterId.ycIsNotEmpty()) {
            mViewModel.getPractiseQuestionList(mChapterId!!)
        } else {
            showSingleBtnDialog(mCommonDialog, "章节id无效，请联系管理员") {
                (activity as StudyContentActivity).switchStudyMaterialFragment()
            }
        }
    }

    /*
    * 处理选项列表数据
    * */
    private fun dealWithOptionList(list: List<OptionEntity>?) {
        mOptionList.clear()
        if (list.ycIsNotEmpty()) {
            list!!.map {
                if (it.isSelect) {
                    mOptionList.add(it)
                }
            }
        }
    }

}
